<template>
  <div>
    <el-container>
      <el-header style="display: flex;justify-content: space-between;align-items: center;padding-left: 0px">
        <el-button
          size="mini"
          type="success"
          @click="exportEmployeeSalary"
        ><i class="fa fa-lg fa-level-down"
            style="margin-right: 5px"></i>导出薪资
        </el-button>
        <div class="block" style="width: 50px; margin-left: -260px">
          <el-date-picker
            v-model="valueMonth"
            align="right"
            type="month"
            @change="searchByDate"
            value-format="yyyy-MM-dd"
            placeholder="请通过月份搜索薪资记录..."
            size="mini">
          </el-date-picker>
        </div>
        <el-button size="mini" type="success" @click="loadSalarySearch" icon="el-icon-refresh">刷新数据</el-button>
      </el-header>
      <el-main style="padding-left: 0px;padding-top: 0px">
        <div>
          <el-card>
            <el-table
              border
              :data="salaries"
              stripe
              id="download"
              v-loading="tableLoading"
              size="mini"
              layout="total, sizes, prev, pager, next, jumper"
              :total="totalCount"
              @selection-change="handleSelectionChange"
              style="width: 100%">
              <el-table-column
                type="selection"
                width="30">
              </el-table-column>
              <el-table-column
                min-width="15%"
                prop="empName"
                align="center"
                label="员工姓名">
              </el-table-column>
              <el-table-column
                width="200"
                min-width="15%"
                prop="workID"
                align="center"
                label="员工工号">
              </el-table-column>
              <el-table-column
                width="200"
                min-width="15%"
                align="center"
                prop="bonus"
                label="奖金">
                <template slot-scope="scope" style="text-align: center;">
                  <el-tag size="small" effect="dark" type="success">{{ scope.row.bonus }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column
                width="200"
                align="center"
                min-width="15%"
                prop="fine"
                label="罚金">
                <template slot-scope="scope" style="text-align: center;">
                  <el-tag size="small" effect="dark" type="danger">{{ scope.row.fine }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column
                prop="monthSalary"
                width="200"
                min-width="15%"
                align="center"
                label="实际工资">
                <template slot-scope="scope" style="text-align: center;">
                  <el-tag size="small" effect="dark" type="primary">{{ scope.row.monthSalary }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column
                prop="month"
                width="200"
                min-width="15%"
                align="center"
                label="薪资月份">
                <template slot-scope="scope" style="text-align: center;">
                  {{ scope.row.month | formatDate1 }}
                </template>
              </el-table-column>
            </el-table>
          </el-card>
        </div>
        <div style="display: flex;text-align: right;justify-content: space-between;margin: 10px 2px 2px;">
          <el-button type="warning" size="mini" icon="el-icon-star-on" @click="jiesuan">薪资结算</el-button>
            <el-pagination
            background
            :page-size="pageSize"
            :current-page="currentPage"
            @size-change="sizeChange"
            @current-change="currentChange"
            layout="total, sizes, prev, pager, next, jumper"
            :total="totalCount">
          </el-pagination>
        </div>
        <el-card style="margin-top: 20px;" shadow="always">
          <div id="mychart" style="float: left;width: 600px;height:400px;"></div>
          <div id="mychart1" style="float: left;width: 600px;height:400px;"></div>
        </el-card>
      </el-main>
    </el-container>
  </div>
</template>
<script>
import * as echarts from "echarts";
import XLSX, {XLSX$Utils} from "xlsx";
import FileSaver from "file-saver";

export default {
  data() {
    return {
      dialogVisible: false,
      tableLoading: false,
      index: 0,
      valueMonth: '',
      salaries: [],
      totalCount: -1,
      currentPage: 1,
      pageSize: 10,
      multipleSelection: [],
      salary: {
        id: '',
        empName: '',
        workID: '',
        bonus: '',
        fine: '',
        monthSalary: '',
        month: ''
      },
      // 柱状图源数据
      metaData: []
    };
  },
  created() {
    this.separateBySalary();
  },
  methods: {
    // 查询根据薪资分段，各阶段员工人数
    separateBySalary() {
      this.getRequest("/salary/search/separate").then(resp => {
        if (resp && resp.status === 200) {
          this.metaData = resp.data;
          console.log(this.metaData)
        }
      })
    },
    // 初始化图表
    initEcharts() {
      const data = [];
      for (let i = 0; i < this.metaData.length; i++) {
        data.push(this.metaData[i])
      }
      console.log(data)
      const option = {
        title: {
          text: "XXX集团 员工薪资分布 柱状图"
        },
        tooltip: {},
        legend: {
          data: ['人数']
        },
        xAxis: {
          data: ["10000-12500", "12500-15000", "15000-17500", "17500-20000", "20000-22500", "22500-25000"]
        },
        yAxis: {},
        series: [
          {
            name: "人数",
            type: "bar", //类型为柱状图
            data: data
          }
        ]
      };
      const myChart = echarts.init(document.getElementById('mychart'));// 图标初始化
      myChart.setOption(option);// 渲染页面
      //随着屏幕大小调节图表
      window.addEventListener("resize", () => {
        myChart.resize();
      });
    },
    initEcharts1() {
      const option = {
        title: {
          text: "XXX集团 员工部门薪资结构图"
        },
        series: [
          {
            name: '薪资结构',
            type: 'pie',    // 设置图表类型为饼图
            radius: '55%',  // 饼图的半径，外半径为可视区尺寸（容器高宽中较小一项）的 55% 长度。
            data: [          // 数据数组，name 为数据项名称，value 为数据项值
              {value: 10000, name: '基本工资'},
              {value: 5000, name: '交通补助'},
              {value: 5000, name: '午餐补助'},
              {value: 4000, name: '奖金'},
              {value: 2000, name: '考勤'}
            ],
            roseType: 'angle',
            itemStyle: {
              normal: {
                shadowBlur: 200,
                shadowColor: 'rgba(0, 0, 0, 0.5)'
              }
            }
          }
        ]
      };
      const myChart = echarts.init(document.getElementById('mychart1'));// 图标初始化
      myChart.setOption(option);// 渲染页面
      //随着屏幕大小调节图表
      window.addEventListener("resize", () => {
        myChart.resize();
      });
    },
    // 导出excel 此方式只能分页导出
    exportExcel() {
      //因为此处有分页，每页展示10条数据，在方法调用的开始，展示所有数据，导出之后再把条数更改过来
      this.pageSize = this.totalCount;
      console.log(this.pageSize);
      let xlsxParam = {raw: true}
      let wb = XLSX.utils.table_to_book(document.querySelector('#download'), xlsxParam);
      /* get binary string as output */
      let wbout = XLSX.write(wb, {bookType: "xlsx", bookSST: true, type: "array",});
      try {
        FileSaver.saveAs(
          new Blob([wbout], {type: "application/octet-stream"}), "员工薪资一览表.xlsx");
      } catch (e) {
        if (typeof console !== "undefined") console.log(e, wbout);
      }
      //在此处更改回来
      this.pageSize = 10;
      this.loadSalarySearch();
      return wbout;
    },
    // 后台导出数据
    exportEmployeeSalary() {
      window.open("/salary/search/exportsalary", "_parent");
    },
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    sizeChange(size) {
      this.pageSize = size;
      this.searchByDate();
    },
    //分页操作
    currentChange(page) {
      this.currentPage = page;
      this.searchByDate();
    },
    //根据时间筛选员工工资记录
    searchByDate() {
      var _this = this;
      if (this.valueMonth !== '' && this.valueMonth !== null) {
        this.getRequest("/salary/search/month/" + this.valueMonth + "?page=" + this.currentPage + "&size=" + this.pageSize).then(resp => {
          this.tableLoading = false;
          if (resp && resp.status === 200) {
            // var data = resp.data;
            // _this.trains = data.trains;
            _this.salaries = resp.data.salaries;
            _this.totalCount = resp.data.count;
          }
        })
      } else {
        this.loadSalarySearch();
      }
    },
    loadSalarySearch() {
      this.tableLoading = true;
      var _this = this;
      this.getRequest("/salary/search/all?page=" + this.currentPage + "&size=" + this.pageSize).then(resp => {
        _this.tableLoading = false;
        if (resp && resp.status === 200) {
          var data = resp.data;
          _this.salaries = data.salaries;
          _this.totalCount = data.count;
        }
      })
    },
    emptySalary() {
      this.salary = {
        id: '',
        empName: '',
        workID: '',
        bonus: '',
        fine: '',
        monthSalary: '',
        month: ''
      };
      this.index = 0;
    }
  },
  mounted: function () {
    this.loadSalarySearch();
    setTimeout(() => {
      //这里写执行的语句即可，先让数据库的数据加载进去数组中，再从数组中取值就好了
      this.initEcharts();
      this.initEcharts1();
    }, 800)
  }
};
</script>
<style>
.el-dialog__body {
  padding-bottom: 10px;
}
</style>
